package yxy.game.pm2.command.union.war;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.Task;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.UnionWarMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.task.TaskHandle;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;
import yxy.game.pm2.module.union.war.UnionWarPlayerModule;

import java.util.Collection;

/** 联盟战 联盟战成就领取 */
@MessageType(proto = Command.UnionWarAchReceive, classtype = UnionWarMessage.UnionWarAchReceiveRequest.class)
public class CMD_UnionWarAchReceive extends Command<UnionWarMessage.UnionWarAchReceiveRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionWarMessage.UnionWarAchReceiveRequest request) {
		String playerCode = messageSource.getTag();
		String code = request.getCode();

		UnionWarMessage.UnionWarAchReceiveResponse.Builder response = UnionWarMessage.UnionWarAchReceiveResponse.newBuilder();

		// 检查是否已经有联盟
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		{
			Result result = new UnionHandle().checkPlayerUnion(entry);
			if (!result.equals(Result.UnionIn)) {
				send(messageSource, response, result);
				return;
			}
		}

		UnionWarPlayerModule unionWarPlayerModule = UnionWarPlayerModule.get(playerCode);
		for (String taskCode : unionWarPlayerModule.getAchievement()) {
			Task task = Task.get(playerCode, taskCode);
			if (task == null) {
				continue;
			}
			if (code.equals(taskCode)) {
				if (!task.isFinish() || task.isReward()) {
					send(messageSource, response, Result.TaskCantReward);// 任务奖励不能领取
				}
				Collection<Currency> rewards = new TaskHandle().rewardTask(playerCode, CCReason.联盟战, task);

				response.setCode(taskCode);
				response.addAllRewards(new CurrencyHandle().packItems(rewards));
				send(messageSource, response, Result.Success);
				return;
			}
		}

		send(messageSource, response, Result.ParamError);
	}

	private void send(MessageSource messageSource, UnionWarMessage.UnionWarAchReceiveResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}